package com.purchase.ml.service.prod.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purchase.ml.bean.base.ApiRestResult;
import com.purchase.ml.bean.req.dealer.DealerProdEditDto;
import com.purchase.ml.bean.req.dealer.DealerProdQueryDto;
import com.purchase.ml.bean.req.prod.SysProdEditDto;
import com.purchase.ml.bean.req.prod.SysProdNewDto;
import com.purchase.ml.bean.req.prod.SysProdQueryDto;
import com.purchase.ml.bean.res.prod.SysProdRes;
import com.purchase.ml.bean.res.prod.SysShopProdRes;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.consts.Constants;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.dealer.SysDealer;
import com.purchase.ml.entity.dealer.SysDealerCategory;
import com.purchase.ml.entity.dealer.SysDealerPruduct;
import com.purchase.ml.entity.prod.SysCategory;
import com.purchase.ml.entity.prod.SysProduct;
import com.purchase.ml.entity.prod.SysProductPic;
import com.purchase.ml.entity.prod.SysProductSku;
import com.purchase.ml.enums.RoleTypeEnum;
import com.purchase.ml.enums.SysSeqNameEnum;
import com.purchase.ml.exception.BizException;
import com.purchase.ml.exception.CommonEnum;
import com.purchase.ml.mapper.dealer.DealerCategoryMapper;
import com.purchase.ml.mapper.dealer.DealerProductMapper;
import com.purchase.ml.mapper.dealer.SysDealerMapper;
import com.purchase.ml.mapper.prod.SysCategoryMapper;
import com.purchase.ml.mapper.prod.SysProdMapper;
import com.purchase.ml.mapper.prod.SysProdPicMapper;
import com.purchase.ml.mapper.prod.SysProdSkuMapper;
import com.purchase.ml.security.JwtUtil;
import com.purchase.ml.service.prod.DealerProductService;
import com.purchase.ml.service.sys.SysUserService;
import com.purchase.ml.service.common.CommonSeqService;
import com.purchase.ml.service.prod.SysProdService;
import com.purchase.ml.utils.FileUploadAndDownUtil;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.purchase.ml.exception.CommonEnum.PRODUCT_EXIST_STOCK;

/**
 * @author :zxm
 * @date :2021/2/25 11:15
 * @description :some description
 **/
@Service
@Slf4j
public class SysProdServiceImpl extends ServiceImpl<SysProdMapper, SysProduct> implements SysProdService {

    @Autowired
    private SysProdMapper prodMapper;
    @Autowired
    private CommonSeqService commonSeqService;
    @Autowired
    private SysProdSkuMapper prodSkuMapper;
    @Autowired
    private SysProdPicMapper prodPicMapper;
    @Autowired
    private SysCategoryMapper categoryMapper;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysDealerMapper dealerMapper;
    @Autowired
    private DealerProductMapper dealerProductMapper;

    @Transactional
    @Override
    public ApiRestResult createProduct(SysProdNewDto prodNewDto) {
        // 前端传过来的是主键id，后端保存的是生成的id
        // 判断目录id是否为空
        SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(prodNewDto.getCategoryId());
        if(sysCategory==null){
            throw new BizException(CommonEnum.NO_EXIST_CATEGORY);
        }
        prodNewDto.setCreatedAt(new Date());

        prodNewDto.setProductId(commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_PROD_GENERATE.getCode()));
        int isSave = prodMapper.insert(prodNewDto);
        if(isSave < 1){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        // 添加sku表
        SysProductSku sku = prodNewDto.getSkuDate();
        sku.setProductId(prodNewDto.getProductId());
        prodSkuMapper.insert(sku);

        // 添加pic表
        List<SysProductPic> picList = prodNewDto.getPicDate();
        for (SysProductPic pic:picList) {
            pic.setProductId(prodNewDto.getProductId());
            prodPicMapper.insert(pic);
        }
        return ApiRestResult.ok();
    }

    @Transactional
    @Override
    public ApiRestResult editProd(SysProdEditDto dto) {
        // 前端传过来的是主键id，后端保存的是生成的id
        // 修改商品表
        SysProduct sysProduct = prodMapper.selectById(dto.getId());
        if(sysProduct==null){
            throw  new BizException(CommonEnum.NO_EXIST_PRODUCT);
        }
        dto.setUpdateAt(new Date());
        if(dto.getCategoryId() != null){
            SysCategory dbCategory = categoryMapper.findCategoryByCategoryId(dto.getCategoryId());
            if(dbCategory == null){
                throw new BizException(CommonEnum.NO_EXIST_CATEGORY);
            }
        }
        int isUpdate = prodMapper.updateById(dto);
        if(isUpdate < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        // 修改sku表
        SysProductSku sku = dto.getProductSku();
        if(sku != null){
            prodSkuMapper.updateById(sku);
        }
        // 修改pic表
        List<SysProductPic> picList = dto.getPicList();
        if(picList != null){
            for (SysProductPic pic:picList) {
                if(pic.getId() == null){
                    pic.setProductId(sysProduct.getProductId());
                    prodPicMapper.insert(pic);
                }else {
                    SysProductPic dbPic = prodPicMapper.selectById(pic);
                    File fileDir = FileUploadAndDownUtil.getImgDirFile();
                    File file = new File(fileDir.getAbsolutePath(), dbPic.getPicUrl());
                    if(file!=null && file.exists() && !dbPic.getPicUrl().equals(pic.getPicUrl())){
                        FileUploadAndDownUtil.deleteFile(file);
                    }
                    prodPicMapper.updateById(pic);
                }
            }
        }
        return ApiRestResult.ok();
    }

    @Override
    public IPage<SysProduct> prodPage(SysProdQueryDto prodQueryDto) {
        log.info("SysProdQueryDto====={}",prodQueryDto);
        IPage<SysProduct> page = new Page<>(prodQueryDto.getPageIndex(),prodQueryDto.getPageNum());
        QueryWrapper<SysProduct> wrapper = new QueryWrapper<>();
        // 处理经销商条件查询
        List<Long> prodIds = new ArrayList<>();
        if(prodQueryDto.getDealerId()!=null){
            SysDealer sysDealer = dealerMapper.selectByDealerId(prodQueryDto.getDealerId());
            if(sysDealer==null){
                return page;
            }
            prodIds = prodMapper.selectProdIds(Constants.DELETE_STATE, prodQueryDto.getDealerId());
            if(prodIds==null || prodIds.size()==0){
                return page;
            }
        }
        // 处理目录条件查询
        if(prodQueryDto.getCategoryId()!=null){
            SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(prodQueryDto.getCategoryId());
            if(sysCategory==null){
                return page;
            }
        }
        // 不查询删除的，若存在条件dealerId，则可查到系统中已删除的商品并使用
        if(prodQueryDto.getDealerId()==null){
            wrapper.ne("`state`",Constants.DELETE_STATE);
        }
        if(prodQueryDto.getDealerId()!=null && prodQueryDto.getState()!=null){
            prodIds = prodMapper.selectProdIdsState(prodQueryDto.getState(), prodQueryDto.getDealerId());
            if(prodIds.size()==0){
                prodIds.add(0L);
            }
            wrapper.in("product_id",prodIds);
        }else {
            wrapper.eq(prodQueryDto.getState()!=null,"state",prodQueryDto.getState());
        }
        wrapper.like(StringUtils.hasText(prodQueryDto.getProductName()),"product_name",prodQueryDto.getProductName());
        wrapper.eq(prodQueryDto.getCategoryId()!=null,"category_id",prodQueryDto.getCategoryId());
        if(prodQueryDto.getSort()!=null && prodQueryDto.getOrder()!=null){
            if(prodQueryDto.getSort()==Constants.ASC_ORDER){
                wrapper.orderByAsc(prodQueryDto.getOrder());
            }else if(prodQueryDto.getSort()==Constants.DESC_ORDER){
                wrapper.orderByDesc(prodQueryDto.getOrder());
            }
        }else {
            wrapper.orderByAsc("id");
        }
        IPage<SysProduct> selectPage = prodMapper.selectPage(page, wrapper);
        List<SysProduct> records = selectPage.getRecords();
        Iterator<SysProduct> it = records.iterator();
        while (it.hasNext()){
            SysProduct product = it.next();
            // 设置图片
            LambdaQueryWrapper<SysProductPic> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysProductPic::getProductId,product.getProductId());
            List<SysProductPic> dbPicList = prodPicMapper.selectList(wrapper1);
            if (dbPicList.size() > 0){
                product.setPicUrl(dbPicList.get(0).getPicUrl());
            }
            // 设置目录名称
            LambdaQueryWrapper<SysCategory> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(SysCategory::getCategoryId,product.getCategoryId());
            SysCategory dbCategory = categoryMapper.selectOne(wrapper2);
            if(dbCategory != null){
                product.setCategoryName(dbCategory.getCategoryName());
            }
            // 设置sku和pic对象
            // 根据产品id查询sku信息
            LambdaQueryWrapper<SysProductSku> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(SysProductSku::getProductId,product.getProductId());
            SysProductSku dbProdSku = prodSkuMapper.selectOne(wrapper3);
            product.setProductSku(dbProdSku);

            // 根据产品id查询pic信息
            LambdaQueryWrapper<SysProductPic> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(SysProductPic::getProductId,product.getProductId());
            List<SysProductPic> dbProdPicList = prodPicMapper.selectList(wrapper4);
            product.setPicList(dbProdPicList);

            if(prodQueryDto.getDealerId()!=null  && records.size()!=0){
                // 设置，商户自己的商品信息
                SysDealerPruduct dbDealerProduct = dealerProductMapper.findBuyerProductByDealerId(prodQueryDto.getDealerId(), product.getProductId());
                if(dbDealerProduct == null){
                    it.remove();
                }else{
                    product.setState(dbDealerProduct.getState());
                    SysProductSku productSku = product.getProductSku();
                    productSku.setStock(dbDealerProduct.getStock());
                    productSku.setMoq(dbDealerProduct.getMoq()!=null?dbDealerProduct.getMoq():productSku.getMoq());
                    productSku.setDeliveryDay(dbDealerProduct.getDeliveryDay()!=null?dbDealerProduct.getDeliveryDay():productSku.getDeliveryDay());
                }
            }
        }
        return selectPage;
    }

    @Override
    public IPage<SysProdRes> dealerProdQuery(DealerProdQueryDto dto) {
        Page<SysProdRes> page = new Page<>(dto.getPageIndex(),dto.getPageNum());
        Long userId = JwtUtil.getUserId();
        SysUser sysUser = userService.getById(userId);
        List<Long> prodIds = prodMapper.selectProdIds(Constants.DELETE_STATE,sysUser.getDealerId());
        if(prodIds==null || prodIds.size()==0){
            return page;
        }
        dto.setProdIds(prodIds);
        if(dto.getCategoryId()!=null){
            SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(dto.getCategoryId());
            if(sysCategory==null){
                return page;
            }
        }
        if(dto.getOrder()!=null && !"".equals(dto.getOrder())){
            StringBuilder sb = new StringBuilder();
            sb.append("`");
            sb.append(dto.getOrder());
            sb.append("`");
            dto.setOrder(sb.toString());
        }

        // 由于mbatis-plus中必须需要实体类才可进行分页查询，故此处，自己写sql语句
        List<SysProdRes> resList = prodMapper.selectProdPages(dto);
        for (SysProdRes prodRes:resList) {
            // 设置sku相关参数
            SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(prodRes.getProductId());
            prodRes.setProductSku(sysProductSku);
            // 设置主经销商自己的库存及商品状态
            SysDealerPruduct dbDealerProduct = dealerMapper.findMerchantStock(sysUser.getDealerId(),prodRes.getProductId());
            prodRes.setState(dbDealerProduct.getState());
            SysProductSku productSku = prodRes.getProductSku();
            productSku.setStock(dbDealerProduct.getStock());
            productSku.setMoq(dbDealerProduct.getMoq()!=null?dbDealerProduct.getMoq():sysProductSku.getMoq());
            productSku.setDeliveryDay(dbDealerProduct.getDeliveryDay()!=null?dbDealerProduct.getDeliveryDay():sysProductSku.getDeliveryDay());
            // 设置目录名称
            SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(prodRes.getCategoryId());
            prodRes.setCategoryName(sysCategory.getCategoryName());
            // 设置经销商图片
            List<SysProductPic> picList = prodPicMapper.selectPicList(prodRes.getProductId());
            prodRes.setPicList(picList);
            if(picList.size() > 0){
                prodRes.setPicUrl(picList.get(0).getPicUrl());
            }
        }
        page.setRecords(resList);
        page.setTotal(resList.size());
        return page;
    }

    @Override
    public ApiRestResult editDealerProd(DealerProdEditDto dto) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        // 根据产品主键id获取产品id
        SysProduct product = prodMapper.selectById(dto);
        dto.setProductId(product.getProductId());
        int i = prodMapper.updateDealerProd(dto,currentUser.getDealerId());
        if(i < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        return ApiRestResult.ok();
    }

    @Override
    public SysProduct findProductByProductId(Long productId) {
        SysProduct product = prodMapper.selectProductByProductId(productId);
        List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
        product.setPicUrl(picList.get(0).getPicUrl());
        return product;
    }

    @Override
    public void batchDeleteProd(List<Long> ids) {
        for (Long id:ids) {
            // 判断要删除的商品是否还存在库存
            SysProduct product = prodMapper.selectById(id);
            SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
            if(sysProductSku.getStock()>0){
                throw new BizException(
                        PRODUCT_EXIST_STOCK.getResultCode(),product.getProductName()+PRODUCT_EXIST_STOCK.getResultMsg());
            }
            int i = prodMapper.updateProdState(id,Constants.DELETE_STATE);
            if(i < 1){
                throw new BizException(CommonEnum.DELETE_ERROR);
            }
        }
    }

    @Override
    public com.purchase.ml.bean.page.Page<SysShopProdRes> shopProdPage(SysProdQueryDto dto) {
        com.purchase.ml.bean.page.Page<SysShopProdRes> page = new com.purchase.ml.bean.page.Page<>(dto.getPageIndex(), dto.getPageNum());
        dto.setState(Constants.NORMAL_STATE);
        //如果是主经销商 查询系统的  否则查询上级商户的
        SysUser sysUser = JwtUtil.getCurrentUser();
        if(Integer.valueOf(CommonConsts.ROLETYPE_MASTER).equals(sysUser.getRoleType())){
            if("price_master_dealer".equals(dto.getOrder())){
                dto.setOrder("final_price_sort");
            }
            List<SysShopProdRes> productList = prodMapper.selectShopProdPages(dto);
            for (SysShopProdRes product:productList) {
                SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
                if(sysProductSku != null){
                    product.setProductSku(sysProductSku);
                }
                List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
                if(picList.size()!=0){
                    product.setPicUrl(picList.get(0).getPicUrl());
                }
            }
            page.setRecords(productList);
            page.setTotal(productList.size());
        }else{
            SysDealer sysDealer = dealerMapper.selectByDealerId(sysUser.getDealerId());
            dto.setDealerId(sysDealer.getSuperior());  // 查询上级主经销商的商店
            if(dto.getOrder()!=null && !"".equals(dto.getOrder())){
                StringBuilder sb = new StringBuilder();
                sb.append("`");
                sb.append(dto.getOrder());
                sb.append("`");
                dto.setOrder(sb.toString());
            }
            // 分页查询经销商拥有的正常商品
            List<SysShopProdRes> dealerProductList = prodMapper.selectDealerProductPage(dto);
            for (SysShopProdRes product:dealerProductList) {
                SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
                if(sysProductSku != null){
                    product.setProductSku(sysProductSku);
                }
                List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
                if(picList.size()!=0){
                    product.setPicUrl(picList.get(0).getPicUrl());
                }
                // 构造属于主经销商自己的数据
                SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(sysDealer.getSuperior(), product.getProductId());
                sysProductSku.setStock(sysDealerPruduct.getStock());
                sysProductSku.setDeliveryDay(sysDealerPruduct.getDeliveryDay());
                sysProductSku.setMoq(sysDealerPruduct.getMoq());
            }
            page.setRecords(dealerProductList);
            page.setTotal(dealerProductList.size());
        }
        return page;
    }

    @Override
    public SysProduct selectProdDetailsById(Long id) {
        SysUser sysUser = JwtUtil.getCurrentUser();
        SysProduct product = prodMapper.selectById(id);
        SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
        if(sysProductSku != null){
            product.setProductSku(sysProductSku);
        }
        List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
        if(picList.size()!=0){
            product.setPicList(picList);
            product.setPicUrl(picList.get(0).getPicUrl());
        }
        SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(product.getCategoryId());
        product.setCategoryName(sysCategory.getCategoryName());
        if(Integer.valueOf(CommonConsts.ROLETYPE_DEALER).equals(sysUser.getRoleType())){
            // 构造属于主经销商自己的数据
            SysDealer sysDealer = dealerMapper.selectByDealerId(sysUser.getDealerId());
            SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(sysDealer.getSuperior(), product.getProductId());
            product.setState(sysDealerPruduct.getState());
            sysProductSku.setStock(sysDealerPruduct.getStock());
            sysProductSku.setDeliveryDay(sysDealerPruduct.getDeliveryDay());
            sysProductSku.setMoq(sysDealerPruduct.getMoq());
        }
        return product;
    }

    private IPage<SysProduct> test(SysProdQueryDto dto){
        Page<SysProduct> page = new Page<>(dto.getPageIndex(), dto.getPageNum());
        dto.setState(Constants.NORMAL_STATE);
        //如果是主经销商 查询系统的  否则查询上级商户的
        SysUser sysUser = JwtUtil.getCurrentUser();
        if(Integer.valueOf(CommonConsts.ROLETYPE_MASTER).equals(sysUser.getRoleType())){
            if("price_master_dealer".equals(dto.getOrder())){
                dto.setOrder("final_price_sort");
            }
//            List<SysProduct> productList = prodMapper.selectShopProdPages(dto);
            List<SysProduct> productList = Collections.emptyList();
            for (SysProduct product:productList) {
                SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
                if(sysProductSku != null){
                    product.setProductSku(sysProductSku);
                }
                List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
                if(picList.size()!=0){
                    product.setPicList(picList);
                    product.setPicUrl(picList.get(0).getPicUrl());
                }
                SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(product.getCategoryId());
                product.setCategoryName(sysCategory.getCategoryName());
            }
            page.setRecords(productList);
            page.setTotal(productList.size());
        }else{
            SysDealer sysDealer = dealerMapper.selectByDealerId(sysUser.getDealerId());
            dto.setDealerId(sysDealer.getSuperior());  // 查询上级主经销商的商店
            if(dto.getOrder()!=null && !"".equals(dto.getOrder())){
                StringBuilder sb = new StringBuilder();
                sb.append("`");
                sb.append(dto.getOrder());
                sb.append("`");
                dto.setOrder(sb.toString());
            }
            // 分页查询经销商拥有的正常商品
            List<SysProduct> dealerProductList = Collections.emptyList();// prodMapper.selectDealerProductPage(dto);
            for (SysProduct product:dealerProductList) {
                SysProductSku sysProductSku = prodSkuMapper.selectProductSkuByProductId(product.getProductId());
                if(sysProductSku != null){
                    product.setProductSku(sysProductSku);
                }
                List<SysProductPic> picList = prodPicMapper.selectPicList(product.getProductId());
                if(picList.size()!=0){
                    product.setPicList(picList);
                    product.setPicUrl(picList.get(0).getPicUrl());
                }
                SysCategory sysCategory = categoryMapper.findCategoryByCategoryId(product.getCategoryId());
                product.setCategoryName(sysCategory.getCategoryName());

                // 构造属于主经销商自己的数据
                SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(sysDealer.getSuperior(), product.getProductId());
                product.setState(sysDealerPruduct.getState());
                sysProductSku.setStock(sysDealerPruduct.getStock());
                sysProductSku.setDeliveryDay(sysDealerPruduct.getDeliveryDay());
                sysProductSku.setMoq(sysDealerPruduct.getMoq());
            }
            page.setRecords(dealerProductList);
            page.setTotal(dealerProductList.size());
        }
        return page;
    }
}
